package com.yitiao.controller;

import com.yitiao.dto.ArticleQueryDTO;
import com.yitiao.dto.PageResult;
import com.yitiao.entity.Article;
import com.yitiao.service.ArticleService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/article")
@AllArgsConstructor
@CrossOrigin
@Slf4j
public class ArticleController {
    private final ArticleService articleService;

    private final RedisTemplate<Object, Object> redisTemplate;

    @GetMapping("/list")
    public PageResult<Article> getArticleList(ArticleQueryDTO articleQueryDTO) {
//        limitByCount();
        return articleService.getArticleList(articleQueryDTO);
    }

    // 限流
    private void limitByCount() {
        String limitName = "count-limit-key";
//        redisTemplate.opsForValue().setIfAbsent(limitName,0,1000, TimeUnit.MILLISECONDS);
        RedisAtomicInteger redisCount = new RedisAtomicInteger(limitName, Objects.requireNonNull(redisTemplate.getConnectionFactory()));
        int count = redisCount.getAndIncrement();
        if (count == 0) {
            // 第一次访问，设置过期时间（统计时间窗口）
            redisCount.expire(1, TimeUnit.SECONDS);
        }
        log.info("the count is [{}].", count);
    }

    @GetMapping("/export/pdf")
    public void exportPdf(HttpServletResponse response) {
        List<Article> articleList = articleService.getAllArticle();

        OutputStream outputStream = null;
        try {
            outputStream = new BufferedOutputStream(response.getOutputStream());
            //生成pdf文件
            articleService.generatePdf(articleList, outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
